package com.easyaop.asm.bytecode.asm;

import com.easyaop.asm.bytecode.MethodInfo;
import lombok.Setter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;

public class RetTargetMethodVisitor extends MethodVisitor implements Opcodes {

    @Setter
    private MethodInfo target;

    public RetTargetMethodVisitor(int api, MethodVisitor methodVisitor) {
        super(api, methodVisitor);
    }

    @Override
    public void visitCode() {}

    Label label = new Label();
    @Override
    public void visitEnd() {

    }

    @Override
    public void visitMaxs(int maxStack, int maxLocals) {
        super.visitLabel(label);
    }

    @Override
    public void visitInsn(int opcode) {

        switch (opcode) {
            case ARETURN:
//                int varIndex = target.maxLocal + 0;
//                varIndex=7;
//                mv.visitVarInsn(ASTORE, varIndex);
//                mv.visitVarInsn(ALOAD, varIndex);
                mv.visitJumpInsn(GOTO, label);
                break;
            case RETURN:
                mv.visitInsn(ACONST_NULL);
                mv.visitJumpInsn(GOTO, label);
                break;
            case IRETURN:
            case FRETURN:
            case DRETURN:
            case LRETURN:
                GeneratorAdapter targetAdapter = new GeneratorAdapter(mv, this.target.access, this.target.name, this.target.descriptor);
                targetAdapter.box(Type.getReturnType(this.target.descriptor));
                mv.visitJumpInsn(GOTO, label);
                break;
            default:
                super.visitInsn(opcode);
        }
    }

}
